package com.ny20231079080.view;

import com.ny20231079080.dao.Impl.ProductDaoImpl;
import com.ny20231079080.dao.ProductDao;
import com.ny20231079080.entity.Managers;
import com.ny20231079080.entity.Orders;
import com.ny20231079080.entity.Products;
import com.ny20231079080.entity.Student;
import com.ny20231079080.service.ManagerService;
import com.ny20231079080.service.OrderService;
import com.ny20231079080.service.ProductService;
import com.ny20231079080.service.StudentService;
import com.ny20231079080.service.impl.ProductServiceImpl;
import com.ny20231079080.service.impl.*;

import java.util.List;
import java.util.Scanner;

public class IndexView {
    private static StudentService studentService = new StudentServicelmpl();
    private static ProductService productService = new ProductServiceImpl();
    private static OrderService orderService = new OrderServiceImpl();
    private static ManagerService managerService = new ManagerServiceImpl();

    public static void main(String[] args) throws Exception {
        boolean flag = true;
        Scanner scanner = new Scanner(System.in);

        while (flag) {
            System.out.println("欢迎来到校园商品系统");
            System.out.println("请选择：");
            System.out.println("1.登录");
            System.out.println("2.注册");
            System.out.println("3.修改个人信息");
            System.out.println("4.管理员登录");
            System.out.println("5.退出");

            int n = scanner.nextInt();

            switch (n) {
                case 1:
                    loginAndPlaceOrder(scanner);
                    break;
                case 2:
                    registerNewStudent(scanner);
                    break;
                case 3:
                    updateStudentInfo(scanner);
                    break;
                case 4:
                    adminLogin(scanner);
                    break;
                case 5:
                    System.out.println("退出系统");
                    flag = false;
                    break;
                default:
                    System.out.println("请输入正确的选择序号！");
            }
        }
    }

    // 处理登录和下单逻辑
    private static void loginAndPlaceOrder(Scanner scanner) throws Exception {
        System.out.println("请登录");
        System.out.print("请输入用户名：");
        String username = scanner.next();
        System.out.print("请输入密码：");
        String password = scanner.next();

        Student student = studentService.login(username, password);
        List<Products> productsList = productService.findAllProducts();

        if (student != null) {
            System.out.println("登录成功！来到商品显示界面");

            if (productsList == null || productsList.isEmpty()) {
                System.out.println("当前无商品信息。");
            } else {
                System.out.println("商品序号\t商品名称\t库存\t价格\t种类\t描述");
                for (Products p : productsList) {
                    System.out.println(p.getProduct_id() + "\t" +
                            p.getName() + "\t" +
                            p.getStock() + "\t" +
                            p.getPrice() + "\t" +
                            p.getCategory() + "\t" +
                            p.getDescription());
                }

                System.out.print("请选择商品序号：");
                int product_id = scanner.nextInt();
                System.out.print("请输入商品数量：");
                int number = scanner.nextInt();

                if (product_id <= 0 || product_id > productsList.size()) {
                    System.out.println("无效的商品序号！");
                    return;
                }

                Products selectedProduct = productsList.get(product_id - 1);
                if (number > selectedProduct.getStock()) {
                    System.out.println("库存不足，下单失败！");
                } else {
                    Orders order = new Orders();
                    order.setStudent_id(student.getStusntid());
                    order.setProduct_id(product_id);
                    order.setNumber(number);
                    order.setTotal_price(selectedProduct.getPrice() * number);

                    int insertOrder = orderService.insertOrder(order);
                    if (insertOrder > 0) {
                        System.out.println("下单成功！");
                    } else {
                        System.out.println("下单失败！");
                    }
                }
            }
        } else {
            System.out.println("用户名或密码错误，请重新登录");
        }
    }

    // 学生注册
    private static void registerNewStudent(Scanner scanner) throws Exception {
        System.out.println("请注册");
        Student s = new Student();

        System.out.print("请输入用户名：");
        s.setName(scanner.next());

        System.out.print("请输入手机号：");
        s.setPhone(scanner.next());

        System.out.print("请输入密码：");
        s.setPassword(scanner.next());

        int insertResult = studentService.insertStudent(s);
        if (insertResult > 0) {
            System.out.println("注册成功！");
        } else {
            System.out.println("注册失败！");
        }
    }

    // 修改个人信息
    private static void updateStudentInfo(Scanner scanner) throws Exception {
        System.out.println("=== 修改个人信息 ===");
        System.out.print("请输入您的学生ID：");
        int studentId = scanner.nextInt();

        Student existingStudent = studentService.findById(studentId);
        if (existingStudent == null) {
            System.out.println("未找到该学生信息！");
            return;
        }

        System.out.println("当前用户名：" + existingStudent.getName());
        System.out.print("请输入新用户名（直接回车保留原值）：");
        String newName = scanner.next();
        if (!newName.isEmpty()) {
            existingStudent.setName(newName);
        }

        System.out.print("请输入新手机号（直接回车保留原值）：");
        String newPhone = scanner.next();
        if (!newPhone.isEmpty()) {
            existingStudent.setPhone(newPhone);
        }

        System.out.print("请输入新密码（直接回车保留原值）：");
        String newPassword = scanner.next();
        if (!newPassword.isEmpty()) {
            existingStudent.setPassword(newPassword);
        }

        int updateResult = studentService.updateStudent(existingStudent);
        if (updateResult > 0) {
            System.out.println("个人信息更新成功！");
        } else {
            System.out.println("个人信息更新失败！");
        }
    }

    // 管理员登录
    private static void adminLogin(Scanner scanner) throws Exception {
        System.out.println("=== 管理员登录 ===");
        System.out.print("请输入管理员用户名：");
        String managerName = scanner.next();
        System.out.print("请输入管理员密码：");
        String managerPassword = scanner.next();

        Managers manager = managerService.login(managerName, managerPassword);
        if (manager != null) {
            System.out.println("管理员登录成功！进入管理界面");

            boolean adminFlag = true;
            while (adminFlag) {
                System.out.println("=== 管理员功能菜单 ===");
                System.out.println("1. 查看所有商品");
                System.out.println("2. 添加商品");
                System.out.println("3. 修改商品");
                System.out.println("4. 删除商品");
                System.out.println("5. 返回主菜单");

                int adminChoice = scanner.nextInt();
                switch (adminChoice) {
                    case 1:
                        viewAllProducts(scanner);
                        break;
                    case 2:
                        addNewProduct(scanner);
                        break;
                    case 3:
                        updateProduct(scanner);
                        break;
                    case 4:
                        deleteProduct(scanner);
                        break;
                    case 5:
                        adminFlag = false;
                        System.out.println("返回主菜单...");
                        break;
                    default:
                        System.out.println("无效选择，请重新输入！");
                }
            }
        } else {
            System.out.println("管理员登录失败，用户名或密码错误！");
        }
    }

    // 查看所有商品
    private static void viewAllProducts(Scanner scanner) throws Exception {
        List<Products> allProducts = productService.findAllProducts();
        if (allProducts == null || allProducts.isEmpty()) {
            System.out.println("暂无商品信息。");
        } else {
            System.out.println("商品序号\t商品名称\t库存\t价格\t种类\t描述");
            for (Products p : allProducts) {
                System.out.println(p.getProduct_id() + "\t" +
                        p.getName() + "\t" +
                        p.getStock() + "\t" +
                        p.getPrice() + "\t" +
                        p.getCategory() + "\t" +
                        p.getDescription());
            }
        }
    }

    // 添加商品
    private static void addNewProduct(Scanner scanner) throws Exception {
        Products product = new Products();

        System.out.print("请输入商品名称：");
        product.setName(scanner.next());

        System.out.print("请输入商品价格：");
        product.setPrice(scanner.nextDouble());

        System.out.print("请输入商品库存：");
        product.setStock(scanner.nextInt());

        System.out.print("请输入商品种类：");
        product.setCategory(scanner.next());

        System.out.print("请输入商品描述：");
        product.setDescription(scanner.next());

        ProductDao productDao = new ProductDaoImpl();
        int result = ((ProductDaoImpl) productDao).insert(product); // 假设已有 insert 方法
        if (result > 0) {
            System.out.println("商品添加成功！");
        } else {
            System.out.println("商品添加失败！");
        }
    }

    // 修改商品
    private static void updateProduct(Scanner scanner) throws Exception {
        System.out.print("请输入要修改的商品ID：");
        int productId = scanner.nextInt();

        ProductDao productDao = new ProductDaoImpl();
        Products product = ((ProductDaoImpl) productDao).findById(productId);
        if (product == null) {
            System.out.println("未找到该商品！");
            return;
        }

        System.out.print("请输入新名称（直接回车保留原值）：");
        String newName = scanner.next();
        if (!newName.isEmpty()) {
            product.setName(newName);
        }

        System.out.print("请输入新价格：");
        product.setPrice(scanner.nextDouble());

        System.out.print("请输入新库存：");
        product.setStock(scanner.nextInt());

        System.out.print("请输入新种类：");
        product.setCategory(scanner.next());

        System.out.print("请输入新描述：");
        product.setDescription(scanner.next());

        int result = ((ProductDaoImpl) productDao).update(product);
        if (result > 0) {
            System.out.println("商品信息更新成功！");
        } else {
            System.out.println("商品信息更新失败！");
        }
    }

    // 删除商品
    private static void deleteProduct(Scanner scanner) throws Exception {
        System.out.print("请输入要删除的商品ID：");
        int productId = scanner.nextInt();

        ProductDao productDao = new ProductDaoImpl();
        int result = ((ProductDaoImpl) productDao).delete(productId);
        if (result > 0) {
            System.out.println("商品删除成功！");
        } else {
            System.out.println("商品删除失败或不存在！");
        }
    }
}
